package com.roy.netty.epoll;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.net.SocketAddress;
import java.nio.charset.Charset;

/**
 * @author ：楼兰
 * @date ：Created in 2021/6/7
 * @description:
 **/

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(" ready to send message to Server");
        final SocketAddress socketAddress = ctx.channel().localAddress();
        ctx.writeAndFlush(Unpooled.copiedBuffer("Hello Server,Client "+socketAddress+" is ready", Charset.forName("utf-8")));
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf)msg;
        System.out.println("received message from server : "+buf.toString(Charset.forName("utf-8")));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
    }
}
